package com.sms.smscode;

import android.Manifest;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.checkbox.MaterialCheckBox;
import com.permissionx.guolindev.PermissionX;
import com.sms.smscode.room.SmsDatabase;
import com.sms.smscode.room.SmsEntity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {


    private boolean mIsChecked = false;
    private TextView tvSms;
    private MaterialCheckBox mcb;
    private TextView tvLog;
    private MainActivity activity;
    private final String[] permissions = new String[]{Manifest.permission.READ_SMS,
            Manifest.permission.RECEIVE_SMS,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};


    private static long handler_times = 180 * 1000; //超过了这个时间的短信就不做处理（毫秒）
    private NestedScrollView scrollView;
    private Disposable disposable;
    private MaterialButton mBtnTest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity = this;
        initView();

        initListener();

        requestPermission();

    }


    private void initView() {
        tvSms = findViewById(R.id.tv_sms);
        mcb = findViewById(R.id.mcb);
        tvLog = findViewById(R.id.tv_log);
        scrollView = findViewById(R.id.scrollView);
        mBtnTest = findViewById(R.id.mBtnTest);
    }

    private void initListener() {
        tvSms.setOnClickListener(v -> {
            SmsListActivity.startAct(MainActivity.this);
        });

        mcb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mIsChecked = isChecked;
                if (isChecked) {
                    toGetSmsCode();
                } else {
                    setDisposable();
                }

            }
        });

        mBtnTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCode("2020-12-12 03:11:33", "667788", new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        sendMsg("异常：" + e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        sendMsg("返回数据：" + response.body().string());
                    }
                });
            }
        });
    }


    //申请短信的权限
    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            PermissionX.init(activity).permissions(permissions).request((allGranted, grantedList, deniedList) -> {
                if (allGranted) {
                } else {
                    Toast.makeText(
                            this,
                            "权限未获取部分功能无法使用",
                            Toast.LENGTH_LONG
                    ).show();
                }
            });

        }
    }


    private void setDisposable() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
    }

    private void toGetSmsCode() {
        setDisposable();
        disposable = Observable.interval(3, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Throwable {

                sms();
            }
        });
    }


    private void sms() {
        final String SMS_URI_INBOX = "content://sms/inbox";

        try {
            Uri uri = Uri.parse(SMS_URI_INBOX);
            String[] projection = new String[]{"_id", "address", "person", "body", "date", "type",};
            Cursor cur = getContentResolver().query(uri, projection, null, null, "date desc limit 10"); // 获取手机内部短信
            // 获取短信中最新的未读短信
            if (cur.moveToFirst()) {
                int index_id = cur.getColumnIndex("_id");
                int index_Address = cur.getColumnIndex("address");
                int index_Person = cur.getColumnIndex("person");
                int index_Body = cur.getColumnIndex("body");
                int index_Date = cur.getColumnIndex("date");
                int index_Type = cur.getColumnIndex("type");

                do {
                    final String strAddress = cur.getString(index_Address);
                    String id = cur.getString(index_id);
                    int intPerson = cur.getInt(index_Person);
                    final String body = cur.getString(index_Body);
                    long longDate = cur.getLong(index_Date);
                    int intType = cur.getInt(index_Type);


                    List<SmsEntity> queryDataById = SmsDatabase.getInstance().smsDao().queryDataById(id);
                    boolean isHaveInsert = queryDataById != null && !queryDataById.isEmpty();

                    if ((System.currentTimeMillis() - longDate <= handler_times) && !isHaveInsert) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date d = new Date(longDate);
                        final String strDate = dateFormat.format(d);

                        String code = getCode(body);
                        if (!TextUtils.isEmpty(code)) {
                            SmsEntity smsEntity = new SmsEntity();
                            smsEntity.body = body;
                            smsEntity.sms_id = id;
                            smsEntity.date = String.valueOf(longDate);
                            smsEntity.add_time = System.currentTimeMillis();
                            smsEntity.address = strAddress;
                            smsEntity.code = code;
                            smsEntity.date = strDate;
                            smsEntity.type = intType;
                            smsEntity.intPerson = intPerson;

                            String platformName = getName(body);
                            final String[] sendMsg = {platformName + "-" + code};
                            try {
                                sendCode(strDate, code, new Callback() {
                                    @Override
                                    public void onFailure(Call call, IOException e) {
                                        sendMsg(sendMsg[0] + "发送异常" + e.getMessage());
                                    }

                                    @Override
                                    public void onResponse(Call call, Response response) throws IOException {
                                        String respBody = response.body().string();


                                        if ("error 0: ".equals(respBody)) {
                                            smsEntity.type = 0;//成功
                                            sendMsg[0] = sendMsg[0] + "已经发送";
                                        } else {
                                            smsEntity.type = 1;//失败
                                            sendMsg[0] = sendMsg[0] + "发送失败";
                                        }


                                        try {
                                            SmsDatabase.getInstance().smsDao().insetData(smsEntity);
                                            sendMsg(sendMsg[0]);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }


                                    }
                                });


                            } catch (Exception e) {
                                Log.i("ZLog", "----");
                                e.printStackTrace();
                            }
                        }
                    }

                } while (cur.moveToNext());

                if (!cur.isClosed()) {
                    cur.close();
                    cur = null;
                }

            } else {
                this.sendMsg("没有新的短信数据需要处理");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            this.sendMsg(ex.getMessage());
        }

    }


    private void sendMsg(String txt) {
        runOnUiThread(() -> {
            if (tvLog.getText().toString().length() > 10000) {
                tvLog.setText("日志定时清理完成..." + "\n\n" + txt);
            } else {
                tvLog.setText(tvLog.getText().toString() + "\n\n" + txt);
            }
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        });

    }

    //"【优酷土豆】您的短信验证码是853211。您的手机号正在使用随机密码登录服务，如非本人操作，请尽快修改密码。"
    Pattern pCode = Pattern.compile("(?<![0-9])([0-9]{" + 6 + "})(?![0-9])");

    private String getCode(String body) {

        Matcher matcher = pCode.matcher(body);
        String smsCode = null;
        while (matcher.find()) {
            String g = matcher.group();
            smsCode = g;
        }
        return smsCode;
    }

    Pattern pName = Pattern.compile("\\【(.*?)\\】");

    private String getName(String body) {
        String name = "";
        Matcher m = pName.matcher(body);
        while (m.find()) {
            name = m.group(1);
        }
        return name;
    }

    //2020-11-12 03:11:33
    private void sendCode(String time, String code, Callback callback) {
        String jsonString = "{\"action\":\"AddWeb\",\"data\":{\"table\":{\"ID\":\"1394848087378TB\",\"row\":{\"ID\":\"1588673925692CATE\",\"web\":{\"ID\":\"1607523520921Web\",\"Name\":\"爱测试\",\"Link\":\"www.a.com\",\"Note\":\"时间:" + time + " 验证码:" + code + "\"},\"index\":\"7\"}}}}";

        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = FormBody.create(mediaType, jsonString);
        Request request = new Request.Builder()
                .url("http://yanglihao.leixiaohua.icu/ResAddApp.aspx?flag=main")
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(callback);
    }


}